package slxy.jiangtao.dts.controller.business;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import slxy.jiangtao.dts.controller.BaseController;
import slxy.jiangtao.dts.core.common.bean.FormCriteria;
import slxy.jiangtao.dts.core.common.bean.FormQuery;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.hibernate.qbc.Page;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.DateUtils;
import slxy.jiangtao.dts.entity.business.Archives;
import slxy.jiangtao.dts.entity.business.Article;
import slxy.jiangtao.dts.entity.business.Summary;
import slxy.jiangtao.dts.entity.sys.DictionariesNews;
import slxy.jiangtao.dts.entity.sys.DictionariesYear;
import slxy.jiangtao.dts.service.sys.DocumentService;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import static com.sun.tools.doclets.formats.html.markup.HtmlStyle.summary;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/5/4.
 * 说明：
 */
@Controller
@RequestMapping("document")
public class DocumentController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(DocumentController.class);
    @Autowired
    CommonService commonService;
    @Autowired
    DocumentService documentService;

    /**
     * 未分类档案首页跳转
     */
    @RequestMapping("archives/index")
    public String archivesIndex(ModelMap modelMap) {
        FormQuery formQuery = new FormQuery("business.Archives");
        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        //默认只显示本年创建的未分类档案
        formCriterias.add(new FormCriteria("creatTime", "like", DateUtils.getDate("yyyy") + "%"));
        Page page = commonService.getPage(formQuery);
        modelMap.addAttribute("page", JSON.toJSONString(page));
        return "document/archives/index";
    }


    /**
     * 删除未分类档案
     *
     * @param archivesId 未分类档案编号
     */
    @RequestMapping("archives/delete/{archivesId}")
    @ResponseBody
    public JSONResult deleteArchives(@PathVariable Integer archivesId, HttpServletRequest request) {
        Archives archives = commonService.get(Archives.class, archivesId);
        try {
            documentService.deleteArchives(archives);
            logger.info(getUserInSession(request).getName() + " 成功删除 " + archives.getName());
        } catch (FileNotFoundException e) {
            logger.error(archives.getName() + "文件已被非法删除");
            return JSONResult.failure("文件已被非法删除");
        }
        return JSONResult.success();
    }

    /**
     * 工作总结首页跳转
     */
    @RequestMapping("summary/index")
    public String summaryIndex(ModelMap modelMap) {
        FormQuery formQuery = new FormQuery("business.Summary");
        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        //默认只显示本年创建的工作总结
        formCriterias.add(new FormCriteria("creatTime", "like", DateUtils.getDate("yyyy") + "%"));
        Page page = commonService.getPage(formQuery);

        //重新封装page中rows的summery
        List<Summary> summaryList = page.getRows();
        /*Optional.ofNullable(summaryList).ifPresent(
                summaries ->
                        summaries.forEach(
                                summary -> {
                                    String year = (commonService.get(DictionariesYear.class, Integer.parseInt(summary.getYear()))).getName();
                                    commonService.evict(summary);
                                    summary.setYear(year);
                                }
                        ));*/
        page.setRows(summaryList);
        modelMap.addAttribute("page", JSON.toJSONString(page));

        List<DictionariesYear> dictionariesYears = commonService.getList(DictionariesYear.class);
        dictionariesYears.sort(Comparator.comparing(DictionariesYear::getId).reversed());//按id降序排列
        modelMap.put("yearList", JSON.toJSONString(dictionariesYears));
        return "document/summary/index";
    }



    /**
     * 删除工作总结档案
     *
     * @param summeryId 工作总结档案编号
     */
    @RequestMapping("summery/delete/{summeryId}")
    @ResponseBody
    public JSONResult deleteSummery(@PathVariable Integer summeryId, HttpServletRequest request) {
        Summary summery = commonService.get(Summary.class, summeryId);
        try {
            documentService.deleteSummery(summery);
            logger.info(getUserInSession(request).getName() + " 成功删除工作笔记 " + summery.getRemark());
        } catch (FileNotFoundException e) {
            logger.error(summery.getRemark() + "文件已被非法删除");
            return JSONResult.failure("文件已被非法删除");
        }
        return JSONResult.success();
    }


    /**
     * 工作总结添加页面跳转
     */
    @RequestMapping(value = "summery/add", method = RequestMethod.GET)
    public String summeryAddGet(ModelMap modelMap) {
        List<DictionariesYear> dictionariesYears = commonService.getList(DictionariesYear.class);
        dictionariesYears.sort(Comparator.comparing(DictionariesYear::getId).reversed());
        modelMap.put("yearList", JSON.toJSONString(dictionariesYears));
        return "document/summary/add";
    }

    /**
     * 工作总结档案添加提交处理
     */
    @RequestMapping(value = "summery/add", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult summeryAddPost(Summary summary, HttpServletRequest request) {
        try {
            summary.setCreatTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
            summary.setCreator(getUserInSession(request).getName());
            commonService.save(summary);
            logger.info(getUserInSession(request).getName() + "上传工作总结成功");
        } catch (Exception e) {
            logger.info(getUserInSession(request).getName() + "上传工作总结失败");
            return JSONResult.failure("上传工作总结失败");
        }
        return JSONResult.success();
    }

    /**
     * 优秀文章首页跳转
     */
    @RequestMapping("article/index")
    public String articleIndex(ModelMap modelMap) {
        FormQuery formQuery = new FormQuery("business.Article");
        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        //默认只显示本年创建的优秀文章
        formCriterias.add(new FormCriteria("creatTime", "like", DateUtils.getDate("yyyy") + "%"));
        Page page = commonService.getPage(formQuery);
        modelMap.addAttribute("page", JSON.toJSONString(page));
        modelMap.put("typeList", JSON.toJSONString(commonService.getList(DictionariesNews.class)));
        return "document/article/index";
    }

    /**
     * 工作总结添加页面跳转
     */
    @RequestMapping(value = "article/add", method = RequestMethod.GET)
    public String articleAddGet(ModelMap modelMap) {
        modelMap.put("typeList", JSON.toJSONString(commonService.getList(DictionariesNews.class)));
        return "document/article/add";
    }

    /**
     * 工作总结档案添加提交处理
     */
    @RequestMapping(value = "article/add", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult articleAddPost(Article article, HttpServletRequest request) {
        try {
            article.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
            article.setCreator(getUserInSession(request).getName());
            commonService.save(article);
            logger.info(getUserInSession(request).getName() + "上传文章成功");
        } catch (Exception e) {
            logger.info(getUserInSession(request).getName() + "上传文章失败");
            return JSONResult.failure("上传文章失败");
        }
        return JSONResult.success();
    }
}
